'use client'
import React, {
  ChangeEvent,
  useImperativeHandle,
  useRef,
  useState,
  ForwardRefRenderFunction,
} from 'react'
import { SSEStatus } from '@/types/chat.d'

interface FooterProps {
  sendMessage: (message: string) => void
  openSetting: () => void
  sendStatus: SSEStatus
}

export interface FooterRef {
  getValue: () => string
  setValue: (val: string) => void
}

const Footer: ForwardRefRenderFunction<FooterRef, FooterProps> = (
  props,
  ref
) => {
  const { sendMessage, sendStatus, openSetting } = props
  const [value, setValue] = useState('')
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const Emoj: Record<SSEStatus, string> = {
    idle: '🚀',
    connecting: '🔄',
    message: '💬',
    error: '❌',
    closed: '🚀',
    aborted: '❌',
  }

  const setTextareaHeight = () => {
    const textarea = textareaRef.current
    if (textarea) {
      textarea.style.height = 'auto' // 重置高度以获取 scrollHeight 正确值
      textarea.style.height = `${Math.min(textarea.scrollHeight, 160)}px` // 最大高度控制
    }
  }

  const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value)
    setTextareaHeight()
  }

  const handleSend = () => {
    if (!value.trim()) return
    sendMessage(value)
    setValue('')
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto'
    }
  }

  const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      handleSend()
      e.preventDefault()
      e.stopPropagation()
    }
  }

  useImperativeHandle(ref, () => ({
    getValue: () => value,
    setValue: (val: string) => {
      setValue(val)
      setTextareaHeight()
    },
  }))

  return (
    <div className="w-full flex justify-center p-1 border-t border-zinc-100 mb-2">
      <div className="w-full lg:w-6/12 xl:w-5/12 max-w-4xl flex-col items-end gap-1 border border-zinc-200 rounded-xl p-2">
        <textarea
          ref={textareaRef}
          value={value}
          onChange={handleChange}
          placeholder="GPT回复内容请自行斟酌,避免输入敏感话题"
          onKeyUp={handleKeyUp}
          className="flex-1 text-sm min-h-[32px] max-h-[160px] p-1 outline-none resize-none bg-transparent code-scrollbar w-full overflow-hidden"
        />
        <div className="flex w-full justify-end mt-1">
          <button
            onClick={openSetting}
            className={`transition-colors cursor-pointer text-blue-500 hover:text-blue-600 mr-3`}
          >
            🛠️
          </button>

          <button
            onClick={handleSend}
            className={`
              transition-colors cursor-pointer
              ${
                !value.trim() ||
                sendStatus === 'connecting' ||
                sendStatus === 'message'
                  ? 'text-gray-400 cursor-not-allowed opacity-50'
                  : 'text-blue-500 hover:text-blue-600'
              }
            `}
            disabled={
              !value.trim() ||
              sendStatus == 'connecting' ||
              sendStatus == 'message'
            }
          >
            {Emoj[sendStatus]}
          </button>
        </div>
      </div>
    </div>
  )
}

export default React.forwardRef(Footer)
